package com.b2c.common.third.templatemsg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;


/**
 * @Description: 发送模板消息
 * pbd add 2019/4/2 9:39
 */
public class WxSendTempletMsg {
    // public static void main(String[] args) {
    //     WxSendTempletParms parms = new WxSendTempletParms();
    //     parms.openId = "o-15E59PfxHSENcIaL1kCFnXAs2I";//ouy_954d2Z-WoPzmi7U6T8nNPO_s
    //     parms.param_1 = "100.00";
    //     parms.param_2 = "sfdasfasfasdfasfasdf";
    //     parms.temletId = WxSendTempletConstants.ZFCG;
    //     parms.url = "http://mall.huayikeji.com/";
    //     String token = "22_q571K3PqrrZhgyReBRk5iZ9_agCRuZ8__5BehAqCBR3q0z0LHJpa72dkURcHl61RyzWA-huxhlFAQ63qMCVaua0x3TX_YNPSgG6Ycd7WohFQySbAz_9ToUkjBZuv9EEvB2lJ-igu444pm7IcEXEdAAAYRY";
    //     sendTempletMsg(token, parms);
    // }

    public static void sendTempletMsg(String token, WxSendTempletParms parms) {
        try {
            System.out.println("发送模板消息的用户openId:" + parms.openId);
            JSONObject jsonObject = createSendJson(parms);
            sendJson(jsonObject.toString(), token);
        } catch (Exception e) {
            System.out.println("wechat发送模板消息异常信息：" + e);
        }
    }
/*    public static void sendTempletMsgs(String token,WxSendTempletParms parms){
        List<String> ids= parms.openIds;
        JSONObject jsonObject=createSendJson(parms);
        for(String open_id:ids){
            if(!StringUtils.isEmpty(open_id)){
                //发送模板消息;
                sendJson(jsonObject.toString(),token);
            }
        }
    }*/

    /**
     * 组装发送json对象
     *
     * @param parms
     * @return
     */
    public static JSONObject createSendJson(WxSendTempletParms parms) {
        WxSendTempletModel wn = new WxSendTempletModel();
        switch (parms.temletId) {
            case WxSendTempletConstants.ZFCG:
                wn.sendTempletZfcg(parms.openId, parms.temletId, parms.url, parms.param_1, parms.param_2);
                break;
            case WxSendTempletConstants.TKCG:
                wn.sendTempletTkcg(parms.openId, parms.temletId, parms.url, parms.param_1, parms.param_2);
                break;
            case WxSendTempletConstants.DDFH:
                wn.sendTempletDdfh(parms.openId, parms.temletId, parms.url, parms.param_1, parms.param_2);
                break;
            case WxSendTempletConstants.DDFX:
                wn.sendTempletDdfx(parms.openId, parms.temletId, parms.url, parms.param_1, parms.param_2);
                break;
        }
        return JSONObject.parseObject(JSON.toJSONString(wn.getMap()));
    }

    /**
     * 发送模板;
     *
     * @param params
     * @param accessToken
     */
    public static JSONObject sendJson(String params, String accessToken) {
        StringBuffer bufferRes = new StringBuffer();
        try {
            URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 请求方式
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            //out.write(URLEncoder.encode(params,"UTF-8"));
            //发送json包
            out.write(params);
            out.flush();
            out.close();
            InputStream in = conn.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String valueString = null;
            while ((valueString = read.readLine()) != null) {
                bufferRes.append(valueString);
            }
            //输出返回的json
            System.out.println(bufferRes);
            in.close();
            if (conn != null) {
                // 关闭连接
                conn.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(bufferRes.toString());
    }

    /**
     * 获取关注列表;
     *
     * @return
     */
    public static ArrayList<String> getUserList(String token) {

        StringBuffer bufferRes = new StringBuffer();

        ArrayList<String> users = null;

        try {

            URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token);

            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();

            // 请求方式

            conn.setDoOutput(true);

            conn.setDoInput(true);

            conn.setRequestMethod("GET");

            conn.setUseCaches(false);

            conn.setInstanceFollowRedirects(true);

            conn.setRequestProperty("Content-Type", "application/json");

            conn.connect();

            // 获取URLConnection对象对应的输入流

            InputStream in = conn.getInputStream();

            BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            String valueString = null;

            while ((valueString = read.readLine()) != null) {

                bufferRes.append(valueString);

            }

            System.out.println(bufferRes);

            in.close();

            if (conn != null) {

                // 关闭连接

                conn.disconnect();

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        //将返回的字符串转换成json

        JSONObject jsonObject = JSONObject.parseObject(bufferRes.toString());

        //解析json中表示openid的列表

        JSONObject data = (JSONObject) jsonObject.get("data");

        if (data != null) {

            //将openid列表转化成数组保存
            data.getJSONArray("openid");
            users = new ArrayList<String>();
            System.out.println(data.getJSONArray("openid"));
            //获取关注者总数

            int count = Integer.parseInt(jsonObject.get("total").toString());

/*            if(count>1000){

                JSONObject object = jsonObject;

                String next_openid = null;

                JSONObject ob_data = null;

                ArrayList<String> ob_user = null;

                //大于1000需要多次获取，或许次数为count/1000

                for(int i=0;i<count/1000;i++){

                    //解析出下次获取的启示openid

                    next_openid = object.get("next_openid").toString();

                    object = getUserJson(next_openid);

                    ob_data = (JSONObject)object.get("data");

                    ob_user = new ArrayList<String>(ob_data.getJSONArray("openid"));

                    for(String open_id : ob_user){

                        //将多次获取的openid添加到同一个数组

                        users.add(open_id);

                    }

                }

            }*/

        }
        return users;

    }

}
